//
//  BaoxianListSelectView.m
//  Qicaishenghuo
//
//  Created by guo on 22/12/16.
//  Copyright © 2015年 vispractice. All rights reserved.
//

#import "BaoxianListSelectView.h"
#import "ColorTool.h"

#define kScreenHeight [[UIScreen mainScreen] bounds].size.height
#define kScreenWidth  [[UIScreen mainScreen] bounds].size.width

#define Size(x) ((x)*kScreenWidth/320.f) // iPhone 6,iPhone 6Plus适配



@interface BaoxianListSelectView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>{
    
    NSMutableArray *sections;
    NSMutableArray *cells;
    UIView *mainView;
    
    
    NSMutableArray *arrselectFirst;
    NSMutableArray *arrselcctSecond;
    
    __block CGFloat heightCollect;
    
}

@property (strong, nonatomic)UICollectionView *collectionView;


@end

@implementation BaoxianListSelectView

- (id)initViewWithTitles:(NSArray*)titles andImages:(NSArray*)btnTitles
{
    self = [super init];
    
    if (self) {
        
        self.max = NSIntegerMax;
        
        self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        self.backgroundColor = [UIColor clearColor];
        
        UILabel *labelback = [UILabel new];
        labelback.backgroundColor = TEXT_BLACK_COLOR;
        labelback.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        labelback.alpha = 0.5;
        [self addSubview:labelback];
        
        arrselectFirst = [@[] mutableCopy];
        arrselcctSecond = [@[] mutableCopy];
        
        sections = [titles mutableCopy];
        cells = [btnTitles mutableCopy];
        
        heightCollect = 20*[titles count] + 60;
        [cells enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            heightCollect = ([cells[idx] count]/4 + 1) * Size(30) +Size(10) + heightCollect;
        }];
        
        if (heightCollect >kScreenHeight) {
            heightCollect = kScreenHeight;
        }
        
        NSLog(@"%f",heightCollect);
        
        mainView = [UIView new];
        mainView.backgroundColor = BACKGROUND_DARK_COLOR;
        mainView.frame = CGRectMake(0, kScreenHeight - heightCollect, Size(320), heightCollect);

        
        //点击视图消失
        UIControl * control = [[UIControl alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        [control addTarget:self action:@selector(dismissSelct) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:control];
        
       
        //确定是水平滚动，还是垂直滚动
        UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
        
        flowLayout.headerReferenceSize = CGSizeMake(kScreenWidth, Size(20));
        
        
        _collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, Size(320), heightCollect - 60) collectionViewLayout:flowLayout];
        self.collectionView.dataSource=self;
        self.collectionView.delegate=self;
        [self.collectionView setBackgroundColor:WHITE_COLOR];
        
        //注册Cell，必须要有
        [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"GHWUICollectionViewCell"];
        
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];

        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterView"];
        
        [mainView addSubview:_collectionView];
        
        
        UIButton *buttonConfirm = [UIButton buttonWithType:UIButtonTypeCustom];
        buttonConfirm.frame = CGRectMake(Size(20), heightCollect - 45, Size(280), 30);
        buttonConfirm.backgroundColor = Navi_yellow;
        buttonConfirm.layer.cornerRadius = 5.0;
        buttonConfirm.titleLabel.font = [UIFont systemFontOfSize:13];
        [buttonConfirm setTitle:@"确定" forState:UIControlStateNormal];
        [buttonConfirm setTitleColor:WHITE_COLOR forState:UIControlStateNormal];
        [buttonConfirm addTarget:self action:@selector(senderNum:) forControlEvents:UIControlEventTouchUpInside];
        [mainView addSubview:buttonConfirm];
        
        [self addSubview:mainView];


        
    }
    return self;

}

#pragma mark - collectiondeledate and datasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return [cells count];
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [cells[section] count] ;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * CellIdentifier = @"GHWUICollectionViewCell";
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor whiteColor];
    
    for (id subView in cell.contentView.subviews) {
        [subView removeFromSuperview];
    }
    NSString *name = cells[indexPath.section][indexPath.row];
    
    
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, Size(67.5), Size(20));
    button.tag = 1034 + indexPath.row + indexPath.section * 1000;
    [button setTitle:name forState:UIControlStateNormal];
    [button setTitle:name forState:UIControlStateHighlighted];
    [button setBackgroundImage:[UIImage imageNamed:@"Not-selected"] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"Not-selected"] forState:UIControlStateHighlighted];
    button.titleLabel.font = [UIFont systemFontOfSize:11];
    [button setTitleColor:TEXT_DARK_COLOR forState:UIControlStateHighlighted];
    [button setTitleColor:TEXT_DARK_COLOR forState:UIControlStateNormal];
    [button addTarget:self action:@selector(selectBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [cell.contentView addSubview:button];
    
    return cell;
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(Size(67.5), Size(20));
}

//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(Size(10), Size(10), Size(10), Size(10));
}
- (UICollectionReusableView *) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableview = nil;
    
    if (kind == UICollectionElementKindSectionHeader)
    {
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
        
        
        reusableview = headerView;
        UILabel *label = [UILabel new];
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont systemFontOfSize:11];
        label.text = sections[indexPath.section];
        label.frame = CGRectMake(Size(20), 0, Size(300), Size(20));
        [reusableview addSubview:label];
        
        reusableview.backgroundColor = BACKGROUND_DARK_COLOR;

    }
    
    return reusableview;
}

#pragma mark -----------

- (void)senderNum:(UIButton*)sender
{
    NSMutableArray *temp1 = [@[] mutableCopy];
    NSMutableArray *temp2 = [@[] mutableCopy];
    
    [arrselectFirst enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [temp1 addObject:cells[0][[arrselectFirst[idx] integerValue]]];
    }];
    [arrselcctSecond enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [temp2 addObject:cells[1][[arrselcctSecond[idx] integerValue]]];
    }];
    
    [self.ghwbaoxianselectdelegate selectFirst:temp1 and:temp2];
    [self dismissSelct];
}

- (void)selectBtn:(UIButton*)sender
{
    
    if (arrselectFirst.count + arrselcctSecond.count >= self.max)
    {
        [[HUDHelper sharedInstance]tipMessage:[NSString stringWithFormat:@"最多只能选择%ld",self.max]];
        return;
    }

    UIButton *button = sender;
    NSInteger section = button.tag/2000;
    NSInteger index = (button.tag - 1034)%1000;
    
    NSLog(@"%zd,%zd",section,index);
    
    if (section == 0) {
        if ([arrselectFirst containsObject:[NSNumber numberWithInteger:index]]) {
            [arrselectFirst removeObject:[NSNumber numberWithInteger:index]];
            [button setBackgroundImage:[UIImage imageNamed:@"Not-selected"] forState:UIControlStateNormal];
            [button setBackgroundImage:[UIImage imageNamed:@"Not-selected"] forState:UIControlStateHighlighted];
            button.titleLabel.font = [UIFont systemFontOfSize:11];
            [button setTitleColor:TEXT_DARK_COLOR forState:UIControlStateHighlighted];
            [button setTitleColor:TEXT_DARK_COLOR forState:UIControlStateNormal];
        }else{
            [arrselectFirst addObject:[NSNumber numberWithInteger:index]];
            [button setBackgroundImage:[UIImage imageNamed:@"selected"] forState:UIControlStateNormal];
            [button setBackgroundImage:[UIImage imageNamed:@"selected"] forState:UIControlStateHighlighted];
            button.titleLabel.font = [UIFont systemFontOfSize:11];
            [button setTitleColor:TEXT_RED_COLOR forState:UIControlStateHighlighted];
            [button setTitleColor:TEXT_RED_COLOR forState:UIControlStateNormal];

        }

    }else{
        if ([arrselcctSecond containsObject:[NSNumber numberWithInteger:index]]) {
            [arrselcctSecond removeObject:[NSNumber numberWithInteger:index]];
            [button setBackgroundImage:[UIImage imageNamed:@"Not-selected"] forState:UIControlStateNormal];
            [button setBackgroundImage:[UIImage imageNamed:@"Not-selected"] forState:UIControlStateHighlighted];
            button.titleLabel.font = [UIFont systemFontOfSize:11];
            [button setTitleColor:TEXT_DARK_COLOR forState:UIControlStateHighlighted];
            [button setTitleColor:TEXT_DARK_COLOR forState:UIControlStateNormal];
        }else{
            [arrselcctSecond addObject:[NSNumber numberWithInteger:index]];
            [button setBackgroundImage:[UIImage imageNamed:@"selected"] forState:UIControlStateNormal];
            [button setBackgroundImage:[UIImage imageNamed:@"selected"] forState:UIControlStateHighlighted];
            button.titleLabel.font = [UIFont systemFontOfSize:11];
            [button setTitleColor:TEXT_RED_COLOR forState:UIControlStateHighlighted];
            [button setTitleColor:TEXT_RED_COLOR forState:UIControlStateNormal];
            
        }

    }
    
}



- (void)show{
    
    self.alpha = 0.0;
    mainView.frame = CGRectMake(0, kScreenHeight, Size(320), 0);
    [UIView animateWithDuration:0.3 animations:^{
        [[UIApplication sharedApplication].keyWindow addSubview:self];
        self.alpha = 1.0;
        mainView.frame = CGRectMake(0, kScreenHeight - heightCollect, Size(320), heightCollect);
    }];
    
}

- (void)dismissSelct{

    [UIView animateWithDuration:0.3 animations:^{
        self.alpha = 0.0;
        mainView.frame = CGRectMake(0, kScreenHeight, Size(320), 0);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];

    }];
    
    
}



@end
